package v1

import (
	"ginblog/model"
	"ginblog/utils/errormsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

var (
	codeArt int
)

// AddArticle 增加文章
func AddArticle(c *gin.Context) {
	var data model.Article
	_ = c.ShouldBindJSON(&data)
	//unitCid, _ := strconv.Atoi(c.Query("cid"))
	//data.Cid = uint(unitCid)
	codeArt = model.AddArticle(&data)
	//if codeArt == errormsg.ERROR {
	//	c.Abort()
	//	c.JSON(http.StatusOK, gin.H{
	//		"code": errormsg.ERROR,
	//		"msg":  errormsg.GetErrorMsg(errormsg.ERROR),
	//	})
	//} else if codeArt == errormsg.SUCCESS {
	//	c.JSON(http.StatusOK, gin.H{
	//		"status":  codeArt,
	//		"message": errormsg.GetErrorMsg(codeArt),
	//		"data":    data,
	//	})
	//}
	c.JSON(http.StatusOK, gin.H{
		"status":  codeArt,
		"data":    data,
		"message": errormsg.GetErrorMsg(codeArt),
	})
}

// FindArt 获取文章列表
func FindArt(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize")) //这里要严格规范大小写 要和前端的参数大小写一致
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1 // -1 表示不使用
	}
	if pageNum == 0 {
		pageNum = -1 // -1 表示不使用
	}
	//调用model下面的查询用户函数
	data, codeArt, total := model.GetArt(pageSize, pageNum)

	c.JSON(http.StatusOK, gin.H{
		"status":  codeArt,
		"message": errormsg.GetErrorMsg(codeArt),
		"data":    data,
		"total":   total,
	})
}

// FindArtInfo 查找单个文章
func FindArtInfo(c *gin.Context) {
	var art model.Article
	id, _ := strconv.Atoi(c.Param("id"))
	art, codeArt = model.GetArtInfo(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  codeArt,
		"message": errormsg.GetErrorMsg(codeArt),
		"data":    art,
	})
}

// FindCateArticles 查找分类下的全部文章
func FindCateArticles(c *gin.Context) {
	var cateArticles []model.Article
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1
	}
	if pageNum == 0 {
		pageNum = -1
	}
	cid, _ := strconv.Atoi(c.Param("cid"))
	var total int64
	cateArticles, codeArt, total = model.GetCateArt(cid, pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":  codeArt,
		"message": errormsg.GetErrorMsg(codeArt),
		"data":    cateArticles,
		"total":   total,
	})
}

// DeleteArt 删除文章
func DeleteArt(c *gin.Context) {
	var art model.Article
	_ = c.ShouldBindJSON(&art)
	id, _ := strconv.Atoi(c.Param("id"))
	codeArt = model.DeleteArt(id)
	if codeArt == errormsg.ERROR {
		codeArt = errormsg.ERROR
	}
	codeArt = errormsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  codeArt,
		"message": errormsg.GetErrorMsg(codeArt),
	})
}

// UpdateArt 编辑文章
func UpdateArt(c *gin.Context) {
	var art model.Article
	id, _ := strconv.Atoi(c.Param("id"))
	_ = c.ShouldBindJSON(&art)

	codeCate = model.UpdateArt(id, &art)
	c.JSON(http.StatusOK, gin.H{
		"status":  codeArt,
		"message": errormsg.GetErrorMsg(codeArt),
	})
}
